const app = getApp();

Component({
  properties: {},
  data: {
    showCreateModal: false,
    showBuiltinBooksModal: false,
    newBookName: '',
    newBookType: 'textbook',
    modalAnimation: null
  },
  lifetimes: {
    attached() {
      const app = getApp();
      this.wordDataManager = app.globalData.wordDataManager;
      this.modalAnimation = wx.createAnimation({ duration: 300, timingFunction: 'ease' });
      // 初始化云开发管理器
      this.cloudManager = app.globalData.cloudManager || app.getCloudManager();
    }
  },
  methods: {
    // 打开创建词书模态框
    openCreateModal() {
      this.setData({ showCreateModal: true });
      setTimeout(() => {
        this.modalAnimation.opacity(1).step();
        this.setData({ modalAnimation: this.modalAnimation.export() });
      }, 10);
    },
    
    // 关闭创建词书模态框
    closeCreateModal() {
      console.log('wb-bottom-actions触发closeCreateModal');
      this.modalAnimation.opacity(0).step();
      this.setData({ modalAnimation: this.modalAnimation.export() });
      setTimeout(() => {
        this.setData({ showCreateModal: false });
        // 触发刷新列表事件
        console.log('wb-bottom-actions触发refreshlists事件');
        this.triggerEvent('refreshlists');
      }, 300);
    },
    
    // 打开选择内置词书模态框改为跳转到词书列表页面
    openBuiltinBooksModal() {
      wx.navigateTo({
        url: '/pages/vocabulary/wordbook-list/wordbook-list'
      });
    },
    
    // 关闭选择内置词书模态框
    closeBuiltinBooksModal() {
      this.modalAnimation.opacity(0).step();
      this.setData({ modalAnimation: this.modalAnimation.export() });
      setTimeout(() => {
        this.setData({ showBuiltinBooksModal: false });
      }, 300);
    },
    
    // 选择内置词书
    onSelectBuiltinBook(e) {
      const { id, name } = e.detail;
      console.log('选择了内置词书:', { id, name });
      
      // 检查词书是否已经导入
      const existingBooks = this.wordDataManager.getAllBooks();
      const existingBook = existingBooks.find(b => b.name === name);
      
      if (existingBook) {
        // 如果词书已存在，显示提示并询问用户是否重新导入
        // wx.showModal({
        //   title: '词书已存在',
        //   content: `"${name}" 词书已经导入。是否重新导入？`,
        //   success: (res) => {
        //     if (res.confirm) {
        //       // 用户确认重新导入
        //       console.log('用户确认重新导入词书:', name);
        //       this.importBuiltinBook(id, name);
        //     }
        //   }
        // });
        wx.showToast({
          title: '词书已存在',
          icon: 'none'
        });
      } else {
        // 词书不存在，直接导入
        this.importBuiltinBook(id, name);
      }
    },
    
    // 导入内置词书
    async importBuiltinBook(bookId, bookName) {
      wx.showLoading({ title: '导入词书...' });
      try {
        // 从云开发环境下载对应的json文件
        const { WORD_BOOKS_PATH_PREFIX } = require('../../../utils/cloudConfig');
        const fileID = `${WORD_BOOKS_PATH_PREFIX}${bookId}.json`;
        
        // 下载文件（默认会自动缓存到本地）
        console.log('开始下载词书文件:', fileID);
        const downloadRes = await this.cloudManager.downloadFile(fileID);
        
        console.log('文件下载结果:', downloadRes);
        
        // 读取文件内容
        const fileContent = await new Promise((resolve, reject) => {
          wx.getFileSystemManager().readFile({
            filePath: downloadRes.tempFilePath,
            encoding: 'utf-8',
            success: res => resolve(res.data),
            fail: err => reject(err)
          });
        });
        
        // 解析JSON文件内容
        const jsonContent = JSON.parse(fileContent);
        
        // 准备词书数据
        const book = {
          id: bookId,
          name: bookName,
          wordCount: jsonContent.wordCount || 0,
          schoolStage: jsonContent.schoolStage || '',
          version: jsonContent.version || '',
          grade: jsonContent.grade || '',
          semester: jsonContent.semester || ''
        };
        
        // 使用解析的JSON内容处理单词
        const lines = jsonContent.content.split('\n');
        const wordIds = [];
        let skippedLines = [];
        
        // 解析每一行单词
        lines.forEach((line, index) => {
          const lineNumber = index + 1;
          if (line.trim()) {
            const parts = line.trim().split(/\t+/);
            if (parts.length >= 2) {
              const english = parts[0];
              const chinese = parts[1];
              // 为每个group元素添加 ${bookId}- 前缀
              const groups = parts.length > 2 ? parts[2].split(';').map(group => `${bookId}-${group}`) : [];
              const categories = parts.length > 3 ? parts[3].split(';') : [];
              
              // 检查单词是否已存在
              // 不仅检查英文单词，还要考虑中文意思，以便区分同形但不同含义的单词
              const words = this.wordDataManager.getAllWords();
              let wordId = Object.keys(words).find(id => 
                words[id].english.toLowerCase() === english.toLowerCase() && 
                words[id].chinese === chinese
              );
              
              // 如果不存在则创建新单词
              if (!wordId) {
                // 检查是否存在相同英文但不同中文的单词
                const hasSameEnglishDifferentChinese = Object.keys(words).some(id => 
                  words[id].english.toLowerCase() === english.toLowerCase() && 
                  words[id].chinese !== chinese
                );
                
                wordId = this.wordDataManager.addWord({
                  english,
                  chinese,
                  categories,
                  groups,
                  bookTranslations: {}
                });
                
                if (hasSameEnglishDifferentChinese) {
                  console.log(`第${lineNumber}行: 新增单词 "${english}"（中文：${chinese}），已存在同名但不同含义的单词`);
                }
              } else {
                console.log(`第${lineNumber}行: 单词 "${english}"（中文：${chinese}）已存在，更新信息`);
                // 如果存在则更新分类、分组
                const currentCategories = words[wordId].categories || [];
                const currentGroups = words[wordId].groups || [];
                const newCategories = [...new Set([...currentCategories, ...categories])];
                const newGroups = [...new Set([...currentGroups, ...groups])];
                
                this.wordDataManager.updateWord(wordId, {
                  categories: newCategories.length > 0 ? newCategories : undefined,
                  groups: newGroups.length > 0 ? newGroups : undefined
                });
              }
              
              wordIds.push(wordId);
            } else {
              console.warn(`第${lineNumber}行: 格式不正确，部分少于2个，跳过该行: "${line}"`);
              skippedLines.push({ lineNumber, content: line });
            }
          } else {
            console.log(`第${lineNumber}行: 空行，跳过`);
          }
        });
        
        // 创建或更新词书
        const existingBooks = this.wordDataManager.getAllBooks();
        const existingBook = existingBooks.find(b => b.name === bookName);
        
        if (existingBook) {
          // 更新现有词书，确保wordIds没有重复
          const uniqueWordIds = [...new Set(wordIds)];
          this.wordDataManager.updateBook(existingBook.id, { 
            wordIds: uniqueWordIds, 
            updateTime: new Date().toISOString() 
          });
          bookId = existingBook.id;
        } else {
          // 创建新词书，确保wordIds没有重复
          const uniqueWordIds = [...new Set(wordIds)];
          bookId = this.wordDataManager.addBook({
            ...book,
            id: bookId,
            type: 'textbook',
            wordIds: uniqueWordIds
          });
        }
        
        // 触发刷新列表事件
        this.triggerEvent('refreshlists');

        // 同步词书单词数据
        // if (bookId && wordIds.length > 0) {
        //   wx.showLoading({ title: '正在同步单词数据...' });
          
        //   this.wordDataManager.syncBookWords(bookId, {
        //     onProgress: (progress) => {
        //       console.log(`单词同步进度: ${progress}%`);
        //     },
        //     onComplete: (results) => {
        //       wx.hideLoading();
        //       wx.showToast({ 
        //         title: `词书导入成功，已同步${results.length}个单词`, 
        //         icon: 'success',
        //         duration: 2000
        //       });
              
        //       // 触发刷新列表事件
        //       this.triggerEvent('refreshlists');
        //     },
        //     onError: (error) => {
        //       wx.hideLoading();
        //       console.error('同步单词数据失败:', error);
        //       wx.showToast({ 
        //         title: '词书导入成功，但单词同步失败', 
        //         icon: 'none'
        //       });
              
        //       // 即使同步失败，也触发刷新列表事件
        //       this.triggerEvent('refreshlists');
        //     }
        //   });
        // } else {
        //   wx.showToast({ title: '词书导入成功', icon: 'success' });
          
        //   // 触发刷新列表事件
        //   this.triggerEvent('refreshlists');
        // }
         wx.showToast({ title: '词书导入成功', icon: 'success' });
      } catch (e) {
        console.error('导入内置词书失败', e);
        wx.hideLoading();
        wx.showToast({ title: '词书导入失败', icon: 'none' });
      }
    },
    
    onNewBookNameInput(e) {
      this.setData({ newBookName: e.detail.value });
    },
    
    selectBookType(e) {
      const { type } = e.detail || e.currentTarget.dataset || {}; 
      if (type) this.setData({ newBookType: type });
    },
    
    confirmCreateBook() {
      const { newBookName, newBookType } = this.data;
      if (!newBookName.trim()) {
        wx.showToast({ title: '请输入词书名称', icon: 'none' });
        return;
      }
      this.wordDataManager.addBook({ name: newBookName, type: newBookType, wordIds: [] });
      this.setData({ showCreateModal: false, newBookName: '', newBookType: 'textbook' });
      wx.showToast({ title: '词书创建成功', icon: 'success' });
    }
  }
});
